<?php
// 接口-生产入库单接口
namespace interface\v1;

use verify;

class machiningInOrderClass extends index
{
	
	private const page    = 'machiningInOrder';
	private const table   = 'machining_in_order';
	private const tableMx = 'machining_in_order_detail';
	private const title   = '生产入库单';
	
	public function search()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			'orderBy' => [
				'创建时间降序',
				'创建时间升序',
				'单据日期降序',
				'单据日期升序',
			],
			'search'  => [
				'line'       => [
					'key'   => 'line',
					'name'  => '生产线',
					'array' => find([
						'table' => 'product_line',
						'field' => "id as value, name as text ",
						'where' => "coid = '" . self::$coid . "'",
					])['array'],
				],
				'recordDate' => [
					'key'   => 'recordDate',
					'name'  => '单据日期',
					'array' => [
						'今天', '近7天', '近30天', '自定义',
					],
				],
				'state'      => [
					'key'   => 'state',
					'name'  => '状态',
					'array' => [
						'草稿', '待确认', '已确认',
					],
				],
			],
		];
	}
	
	/**
	 * 列表
	 *
	 * @return void
	 */
	public function list()
	{
		$where = '';
		//获取查询结果
		$where .= search([
			"="    => [
				'coid'   => self::$coid,
				'state'  => $this->post('state'),
				'lineId' => $this->post('line'),
			],
			'like' => [
				'orderNo' => $this->post('orderNo'),
			],
		]);
		//单据日期
		if ($this->post('recordDate')) {
			$where .= self::miniTimeComparison($this->post('recordDate'), 'date', 'recordDate');
		}
		$orderBy      = $this->post('orderBy') ?: '创建时间降序';
		$orderByArray = $this->orderBy([
			"search"  => $orderBy,
			"default" => "创建时间降序",
			"array"   => [
				"time"       => ["asc" => "创建时间升序", "desc" => "创建时间降序", "site" => 1],
				"recordDate" => ["asc" => "单据时间升序", "desc" => "单据时间降序", "site" => 2],
			],
		]);
		$page         = $this->page(["table" => self::table, "where" => $where, "order" => $orderByArray['orderBy']]);
		//数据分析
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$line             = query('product_line', "id = '$array[lineId]'");
			$total            = find([
				'table'  => self::tableMx,
				'field'  => " sum(num) as num, sum(money + fee + energyFee) as money",
				'single' => "orderId = '$array[id]'",
			]);
			$data['result'][] = [
				"id"        => $array['id'],
				'unit'      => static::$unit,
				'orderNo'   => $array['orderNo'],
				'line'      => $line['workshop'] . '-' . $line['name'],
				"state"     => $array['state'],
				'staffName' => self::findStaff($array['manager']),
				'num'       => $total['num'],
				'money'     => $total['money'],
				'time'      => self::formatDate($array['time'], 'Y/m/d'),
			];
		}
		$data['page']    = $page['para'];
		$data['orderBy'] = $orderBy;
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	
	/**
	 * 选择物料
	 */
	public function material()
	{
		$materialId = $this->post('materialSkuId') ? explode(',', $this->post('materialSkuId')) : [];
		$where      = " 1=1 and b.id not in ('" . implode("','", $materialId) . "')";
		$and        = " AND a.coid = '" . self::$coid . "' ";
		if ($this->post('wd')) {
			$and .= " AND (a.name like '%{$this->post('wd')}%' OR code like '%{$this->post('wd')}%') ";
		}
		$equal   = [
			'a.state' => '启用',
		];
		$where   .= search(["=" => $equal]) . $and;
		$orderBy = $this->orderBy([
			"search"  => $this->post('orderBy') ?: null,
			"default" => "创建时间降序",
			"array"   => [
				"b.time"       => ["asc" => "创建时间升序", "desc" => "创建时间降序", "site" => 2],
				"b.updateTime" => ["asc" => "更新时间升序", "desc" => "更新时间降序", "site" => 3],
			],
		]);
		$page    = $this->page([
			"table"   => "material as a join material_sku as b on a.id = b.materialId",
			"field"   => "a.*, b.name as skuName, b.id as materialSkuId",
			"where"   => " $where ",
			'pageNum' => 50,
			"order"   => $orderBy['orderBy'],
		]);
		$result  = [];
		//获取记录
		foreach ($page['array'] as $array) {
			$inventoryNum = inventoryBalanceClass::inventoryNum($array['materialSkuId']);
			$result[]     = [
				'materialId'      => $array['id'],
				'materialSkuId'   => $array['materialSkuId'],
				'name'            => $array['code'] . ' ' . $array['name'] . $array['model'],
				'brand'           => $array['brand'],
				'model'           => $array['model'],
				'materialSkuName' => $array['skuName'],
				'num'             => $inventoryNum,
				'unit'            => $array['unit'],
				'availableNum'    => $inventoryNum,
			];
		}
		$orderByArr         = [
			'创建时间降序',
			'创建时间升序',
			'更新时间降序',
			'更新时间升序',
		];
		$this->resp['data'] = [
			'result'  => $result,
			'page'    => $page['para'],
			'orderBy' => $orderByArr,
		];
		$this->code         = 1;
	}
	
	
	/**
	 * 编辑
	 */
	public function edit(): void
	{
		// 解析字符串
		$detail           = !empty($_POST['detail']) ? json_decode($_POST['detail'], true) : [];
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: inStockClass::getArrVal('id', $detail);
		$materialSkuIdArr = $this->post('materialSkuId') ?: inStockClass::getArrVal('materialSkuId', $detail);
		$numArr           = $this->post('num') ?: inStockClass::getArrVal('num', $detail);
		$priceArr         = $this->post('price') ?: inStockClass::getArrVal('price', $detail);
		$unitArr          = $this->post('unit') ?: inStockClass::getArrVal('unit', $detail);
		$warehouseArr     = $this->post('warehouseId') ?: inStockClass::getArrVal('warehouseId', $detail);
		$mxTextArr        = $this->post('mxText') ?: inStockClass::getArrVal('mxText', $detail);
		$feeArr           = $this->post('mxfee') ?: inStockClass::getArrVal('fee', $detail);
		$energyFeeArr     = $this->post('mxenergyFee') ?: inStockClass::getArrVal('energyFee', $detail);
		$sourceIdArr      = $this->post('mxSourceId') ?: inStockClass::getArrVal('sourceId', $detail);
		$field            = [
			'lineId'     => $this->post('lineId'),
			'manager'    => $this->post('manager'),
			'fee'        => $this->post('fee'),
			'energyFee'  => $this->post('energyFee'),
			'recordDate' => $this->post('recordDate'),
			'text'       => $this->post('text'),
		];
		$annotation       = [
			'lineId'     => '生产线',
			'manager'    => '经手人',
			'recordDate' => '单据日期',
			'text'       => '备注',
		];
		$rules            = [
			'lineId'     => 'required',
			'manager'    => 'required',
			'recordDate' => 'required|date',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " coid = '" . self::$coid . "' AND id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (self::is_null_array($mxIdArr)) {
			$this->resp['warn'] = '请选择产品明细';
		} elseif (self::is_null_array($materialSkuIdArr)) {
			$this->resp['warn'] = '请选择产品明细';
		} elseif (self::is_null_array($numArr)) {
			$this->resp['warn'] = '数量请填写完整';
		} elseif (self::is_null_array($warehouseArr)) {
			$this->resp['warn'] = '请选择仓库';
		} elseif (self::is_null_array($priceArr)) {
			$this->resp['warn'] = '价格请填写完整';
		} elseif (self::is_null_array($unitArr)) {
			$this->resp['warn'] = '请选择单位';
		} elseif (self::is_null_array($feeArr)) {
			$this->resp['warn'] = '请输入分担制造费';
		} elseif (self::is_null_array($energyFeeArr)) {
			$this->resp['warn'] = '请输入分担能耗费';
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$this->resp['warn'] = '此生产入库单已确认，不能修改';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (empty($info['id'])) {
				$orderNo            = self::generateCode(self::page,[
                    'prefix' => 'SCRK' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ],$field);
				$field              = array_merge($field, [
					'id'      => $id,
					'orderNo' => $orderNo,
					'state'   => '草稿',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$this->resp['warn'] = static::insert(["table" => self::table, "field" => $field,]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			//添加或更新生产入库单明细
			if (is_array($mxIdArr)) {
				foreach ($mxIdArr as $k => $nid) {
					$nid = strlen($nid) > 20 ? self::getId() : $nid;
					$mx          = query(self::tableMx, "id = '$nid'");
					$materialSku = query('material_sku', "id = '$materialSkuIdArr[$k]'");
					if (!empty($mx['id'])) {
						//更新
						$warn = static::update([
							"table" => self::tableMx,
							"field" => [
								'materialId'    => $materialSku['materialId'],
								'materialSkuId' => $materialSkuIdArr[$k],
								'num'           => $numArr[$k],
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'coid'          => self::$coid,
								'warehouseId'   => $warehouseArr[$k],
								'fee'           => $feeArr[$k],
								'energyFee'     => $energyFeeArr[$k],
								'money'         => round($numArr[$k] * $priceArr[$k], 2),
								'text'          => $mxTextArr[$k],
								'sourceId'      => !empty($sourceIdArr[$k]) ? $sourceIdArr[$k] : '',
							],
							"where" => " id = '$nid'",
						]);
					} else {
						//新增
						$warn = static::insert([
							"table" => self::tableMx,
							"field" => [
								'id'            => $nid,
								'coid'          => self::$coid,
								'orderId'       => $id,
								'materialId'    => $materialSku['materialId'],
								'materialSkuId' => $materialSkuIdArr[$k],
								'num'           => $numArr[$k],
								'price'         => $priceArr[$k],
								'unit'          => $unitArr[$k],
								'warehouseId'   => $warehouseArr[$k],
								'fee'           => $feeArr[$k],
								'energyFee'     => $energyFeeArr[$k],
								'money'         => round($numArr[$k] * $priceArr[$k], 2),
								'text'          => $mxTextArr[$k],
								'sourceId'      => !empty($sourceIdArr[$k]) ? $sourceIdArr[$k] : '',
							],
						]);
					}
					if (!in_array($warn, ['新增成功', '更新成功'])) {
						$isPass             = false;
						$this->resp['warn'] = $warn;
						break;
					}
				}
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				// 更新金额
				delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code         = 1;
				$this->resp['data'] = $id;
			} else {
				$this->rollback();
			}
		}
		
		resp:
	}
	
	/**
	 * 提交
	 */
	public function commit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state' => '待确认',
		];
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此生产入库单';
		} elseif ($info['state'] != '草稿') {
			$this->resp['warn'] = '此生产入库单不是草稿状态，不能提交';
		} else {
			$this->resp['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				auditingFollow([
					"type"   => "生产入库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】提交",
				]);
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
		resp:
	}
	
	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$this->resp['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = '未找到此生产入库单';
		} elseif ($info['state'] != '待确认') {
			$this->resp['warn'] = '此申请不是待确认状态，不能确认';
		} else {
			$this->resp['warn'] = update([
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			]);
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				auditingFollow(array(
					"type"   => "生产入库单",
					"typeId" => $info['id'],
					"text"   => "【{$this->control['name']}】确认",
				));
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
		resp:
	}
	
	/**
	 * 删除
	 *
	 * @return void
	 */
	public function delete(): void
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(["table" => self::table, "where" => " id = '$id' "]);
					delete(["table" => self::tableMx, "where" => " orderId = '$id' "]);
					delete(["table" => 'auditing_follow', "where" => " typeId = '$id' "]);
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 详情
	 *
	 * @return void
	 */
	public function detail()
	{
		$id   = $this->post('id');
		$info = query(self::table, "id = '" . $id . "'");
		if (!in_array(self::$stid, [$info['checkId'], $info['manager'], $info['stid']])) {
			$this->resp['warn'] = '这不是您的' . self::title;
		} elseif (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['id'])) {
			$this->resp['warn'] = "未找到此" . self::title;
		} else {
			$audit      = find([
				'table' => 'auditing_follow',
				'where' => " typeId = '$info[id]' order by time desc",
			]);
			$result     = find([
				'table' => self::tableMx,
				'where' => " orderId = '$info[id]' ",
			]);
			$detail     = [];
			$totalMoney = 0;
			foreach ($result['array'] as $value) {
				$material             = query('material', " id = '$value[materialId]' ");
				$materialSku          = query('material_sku', " id = '$value[materialSkuId]' ");
				$warehouse            = query('warehouse', " id = '$value[warehouseId]' ");
				$detail[$value['id']] = [
					'id'            => $value['id'],
					'code'          => $material['code'],
					'name'          => $material['name'],
					'skuName'       => $materialSku['name'],
					'brand'         => $material['brand'],
					'model'         => $material['model'],
					'unit'          => $material['unit'],
					'price'         => $value['price'],
					'num'           => $value['num'],
					'text'          => $value['text'],
					'warehouse'     => $warehouse['name'],
					'warehouseId'   => $warehouse['id'],
					'materialId'    => $value['materialId'],
					'materialSkuId' => $value['materialSkuId'],
					'fee'           => $value['fee'],
					'energyFee'     => $value['energyFee'],
					'total'         => $value['num'] * $value['price'] + $value['fee'],
					'sourceId'      => $value['sourceId'],
				];
				$totalMoney           += $value['num'] * $value['price'] + $value['fee'];
			}
			$line           = query('product_line', "id = '$info[lineId]'");
			$data['result'] = [
				'info'        => [
					"id"         => $info['id'],
					'staffName'  => self::findStaff($info['manager']),
					'manager'    => $info['manager'],
					'orderNo'    => $info['orderNo'],
					'recordDate' => $info['recordDate'],
					'workshop'   => $line['workshop'],
					'lineName'   => $line['name'],
					'lineId'     => $info['lineId'],
					"state"      => $info['state'],
					'text'       => $info['text'],
					'fee'        => $info['fee'],
					'energyFee'  => $info['energyFee'],
					'date'       => self::formatDate($info['time'], 'm/d'),
				],
				'detail'      => $detail,
				'auditRecord' => $audit['array'],
				'total'       => [
					'num'   => count($detail),
					'money' => $totalMoney,
				],
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 关联生产计划单
	 *
	 * @return void
	 */
	public function getOrderNo(): void
	{
		$equal = [
			'state'   => '已确认',
			'isClose' => 0,
			'coid'    => self::$coid,
		];
		$where = search(["=" => $equal]);
		$page  = find([
			'field'   => 'id as value, orderNo as text ',
			"table"   => "machining_order",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "`time` desc",
		]);
		//返回
		$this->code         = 1;
		$this->resp['data'] = $page['array'];
	}
	
	/**
	 * 根据计划单获取物流
	 */
	public function getMaterial()
	{
		$mxIdArr = $this->post('machiningOrderId') ? [$this->post('machiningOrderId')] : [];
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$this->resp['warn'] = '请选择生产计划单';
		} else {
			$data = [];
			foreach ($mxIdArr as $machiningOrderId) {
				$materials = find([
					'table' => 'machining_order_mx',
					'where' => "orderId = '$machiningOrderId' order by list asc",
				]);
				foreach ($materials['array'] as $array) {
					$machining_order = query('machining_order', "id = '$array[orderId]'");
					$materialSku     = query('material_sku', "id = '$array[materialSkuId]'");
					$material        = query('material', "id = '$materialSku[materialId]'");
					$id              = self::generateId([
						'material_sku' => $materialSku['id'],
						'sourceId'     => $array['id'],
					]);
					$data[$id]       = [
						'id'            => $id,
						'sourceId'      => $array['id'],
						'code'          => $material['code'],
						'name'          => $material['name'],
						'skuName'       => $materialSku['name'],
						'brand'         => $material['brand'],
						'model'         => $material['model'],
						'unit'          => $material['unit'],
						'price'         => 0,
						'num'           => 0,
						'text'          => '',
						'warehouse'     => '请选择',
						'warehouseId'   => '',
						'materialId'    => $material['id'],
						'materialSkuId' => $materialSku['id'],
						'fee'           => 0,
						'energyFee'     => 0,
						'total'         => 0,
					];
				}
			}
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	/**
	 * 工人计件
	 */
	function peopleFee($machiningOrderMxId): float
	{
		$money            = 0;
		$machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
		$sendAll          = find(array('table' => "machining_send_order", 'where' => "machiningOrderMxId = '$machiningOrderMxId' and state = '已确认' order by time asc"));
		foreach ($sendAll['array'] as $sendOrder) {
			$all = find(array('table' => "process_report", 'where' => "sendId = '$sendOrder[id]' and state = '已确认'"));
			foreach ($all['array'] as $array) {
				$routing_detail          = query('routing_detail', "orderId = '$machiningOrderMx[routingId]' and processId = '$array[processId]'");
				$routing_detail['price'] = $routing_detail['price'] ?: 0;
				$money                   += material_num_change($machiningOrderMx['materialSkuId'], $routing_detail['unit'], $machiningOrderMx['unit']) * $array['yield'] * $routing_detail['price'];
			}
		}
		return round($money, 2);
	}
	
	/**
	 * 分摊费用
	 */
	function inFee($machiningOrderMxId): array
	{
		$productFee       = $eneryFee = 0;
		$num              = 0;//实际产量
		$machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
		$all              = find(array('table' => "machining_in_order as a join machining_in_order_detail as b on a.id = b.orderId", 'field' => "b.materialSkuId,b.num,b.unit,b.energyFee,b.fee", 'where' => "b.sourceId = '$machiningOrderMxId' and a.state = '已确认' and a.coid = '" . self::$coid . "' order by b.list asc"));
		foreach ($all['array'] as $array) {
			$num        += material_num_change($array['materialSkuId'], $array['unit'], $machiningOrderMx['unit'], $array['num']);
			$productFee += $array['fee'];
			$eneryFee   += $array['energyFee'];
		}
		return ['productFee' => $productFee, 'energyFee' => $eneryFee, 'num' => $num];
	}
	
	function material_num_change($materialSkuId, $from, $to, $num = 1): int|float
	{
		$num                    = $num ?: 0;
		$materialSku            = query('material_sku', " id = '$materialSkuId'");
		$material               = query('material', " id = '$materialSku[materialId]'");
		$materialSku['unitOne'] = (float)$materialSku['unitOne'];
		$materialSku['unitTwo'] = (float)$materialSku['unitTwo'];
		if ($from == $material['unit_one']) {
			$num = $materialSku['unitOne'] * $num;
		} elseif ($from == $material['unit_two']) {
			$num = $materialSku['unitTwo'] * $num;
		}
		
		if ($to == $material['unit_one']) {
			$num = $materialSku['unitOne'] > 0 ? round($num / $materialSku['unitOne'], 2) : 0;
		} elseif ($to == $material['unit_two']) {
			$num = $materialSku['unitTwo'] > 0 ? round($num / $materialSku['unitTwo'], 2) : 0;
		}
		return $num;
	}
	
	/**
	 * 材料耗用
	 */
	function materialFee($machiningOrderMxId): float
	{
		$money            = 0;
		$machiningOrderMx = query('machining_order_mx', "id = '$machiningOrderMxId'");
		$all              = find(array(
			'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId", 'field' => "b.materialSkuId,b.unit,ifnull(sum(any_value(b.num)),0) as num",
			'where' => "a.state = '已确认' and a.type=0 and b.sourceId in (select id from machining_order_detail where orderId = '$machiningOrderMx[orderId]' and state = '已确认') group by b.materialSkuId,b.unit",
		));
		foreach ($all['array'] as $array) {
			$price = inventoryBalanceClass::unitPrice($array['materialSkuId']);
			//退料数量
			$returnNum = 0;
			$returnAll = find(array(
				'table' => "pick_order as a join pick_order_detail as b on a.id = b.orderId", 'field' => "b.*", 'where' => "a.state = '已确认' and a.type=1 and
                 b.sourceId in (select d.id from pick_order as c join pick_order_detail as d on c.id = d.orderId where d.materialSkuId = '$array[materialSkuId]' and c.state = '已确认' and c.type = 0 and d.sourceId in (select id from machining_order_detail where orderId = '$machiningOrderMx[orderId]' and state = '已确认')) ",
			));
			foreach ($returnAll['array'] as $returnMaterail) {
				$returnNum += material_num_change($returnMaterail['materialSkuId'], $returnMaterail['unit'], $array['unit'], $returnMaterail['num']);
			}
			$array['num'] = $array['num'] - $returnNum;
			$money        += material_num_change($array['materialSkuId'], $array['unit'], $machiningOrderMx['unit'], $array['num']) * $price;
		}
		return round($money, 2);
	}
	
	function unitOption($materialId): array
	{
		$material     = query('material', " id = '$materialId'");
		$unitOption[] = $material['unit'];
		if ($material['unit_one']) {
			$unitOption[] = $material['unit_one'];
		}
		if ($material['unit_two']) {
			$unitOption[] = $material['unit_two'];
		}
		return array_filter($unitOption);
	}
	
}

